
const Koa = require('koa');
const router = require('koa-router')();
const { defineModel, DataTypes, sequelize } = require('./db');

let app = new Koa();
let port = 3030;


// 定义一个student模型
let stu = defineModel('student', {
  studentName: DataTypes.STRING(80),
  studentAge: DataTypes.BIGINT
});

app.use(router.routes());

(async () => {
  try {
    sequelize.authenticate();
    console.log('连接成功');
  } catch (error) {
    console.log('连接失败');
  }
})()


app.use(async (ctx, next) => {

  console.log(Date.now());

  if (ctx.status == 404) {
    ctx.body = "404"
  }
  await next();

})

// let selectSql="select * from student"

//向模型插入数据
router.get('/inster', async () => {
  try {
    await stu.create({ studentName: "admin", studentAge: 19 })
    console.log("插入成功");
  } catch (error) {
    console.log("插入失败");
  }
})


// 将模型同步到表
// (async () => {
//   await stu.sync({});
// })();

router.get('/stu', async ctx => {
  ctx.body = await stu.findAll();
})


// router.post('/', async ctx => {
//   console.log("ctx.request.body", ctx.request.body)   
//   console.log("ctx.request.files", ctx.request.files)     //文件
//   console.log("ctx.request.fields", ctx.request.fields) //表单
//   let { title, catalogs, tags, contents } = ctx.request.fields
//   console.log(title, catalogs, tags, contents)
//   Article.create({ title: title, catalogs: catalogs, tags: tags, content: contents })
// })

app.listen(port, () => {
  console.log(`http://127.0.0.1:${port}`);
})